<?php

class ControllerLocalisationCarrier extends AdminController {
	public function index() {
		M('localisation/carrier', 'carrier');
		$this->getList();
	}

	public function insert() {
		M('localisation/carrier', 'carrier');
		
		if ($this->request->isPost() && $this->validateForm()) {

			$this->carrier->addCarrier($this->request->post);

			$this->session->set_flashdata('success', $this->_['text_success']);
			$this->redirect(UA('localisation/carrier'));
		}
		
		$this->getForm();
	}

	public function update() {
		M('localisation/carrier', 'carrier');
		
		if ($this->request->isPost() && $this->validateForm()) {
			$this->carrier->editCarrier($this->request->get['carrier_id'], $this->request->post);
			$this->session->set_flashdata('success', $this->_['text_success']);
			$this->redirect(UA('localisation/carrier'));
		}
		$this->getForm();
	}

	public function delete() {
		M('localisation/carrier', 'carrier');
		if (isset($this->request->post['selected'])) {
			$this->carrier->deleteCarrier($this->request->post['selected']);
			$this->session->set_flashdata('success', $this->_['text_success']);
			$this->redirect(UA('localisation/carrier'));
		}
		$this->getList();
	}
	
	protected function getForm() {
		$this->document->setTitle($this->_['heading_title']);
		
		$carrier_id = G('carrier_id');
		
		if ($carrier_id) {
			$this->data['action'] = UA('localisation/carrier/update', "carrier_id=$carrier_id");
			if (!$this->request->isPost()) {
				$this->vo->data = $this->carrier->getCarrier($carrier_id);
			}
		}
		else {
			$this->data['action'] = UA('localisation/carrier/insert');
		}
		
		$this->display('localisation/carrier_form.tpl');
	}
	
	protected function getList() {
		$this->document->setTitle($this->_['heading_title']);
		
		$qf = new Query_filter();
		$total = $this->carrier->getTotalCarriers();
		$this->data['carriers'] = $this->carrier->getCarriers($qf);
		$this->data['pagination'] = $this->pagination($total)->render();
		
		$this->display('localisation/carrier_list.tpl');
	}
	
	public function validateForm() {
		$this->load->library('form_validation', true);
		$this->form_validation->set_rules('code', $this->_['text_code'], 'required');
		$this->form_validation->set_rules('name', $this->_['text_name'], 'required');
		return $this->form_validation->run();
	}
}